package com.example.forumadminbackend.config;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.forumadminbackend.util.JwtUtil;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");

        if (token == null || token.isEmpty()) {
            token = request.getParameter("token"); // 尝试从 URL 参数中获取令牌
        }

        if (token == null || token.isEmpty()) {
            response.setStatus(401);
            response.getWriter().write("未登录或token缺失");
            return false;
        }

        try {
            // 移除 "Bearer " 前缀
            token = token.replace("Bearer ", "");
            DecodedJWT decodedJWT = JwtUtil.parseToken(token);

            // 从 DecodedJWT 中获取 claims
            String adminId = decodedJWT.getClaim("adminId").asString();
            String username = decodedJWT.getClaim("username").asString();

            request.setAttribute("adminId", adminId);
            request.setAttribute("username", username);

            return true;
        } catch (JWTVerificationException e) {
            response.setStatus(401);
            response.getWriter().write("无效的token: " + e.getMessage());
            return false; // Token验证失败，拒绝请求
        } catch (Exception e) {
            response.setStatus(500);
            response.getWriter().write("服务器内部错误: " + e.getMessage());
            return false;
        }
    }
} 